/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.system.domain.OnlineLog;
import com.koron.system.domain.OperationLog;
import com.koron.system.domain.SigninLog;
import com.koron.system.service.api.LogService;
import com.koron.system.utils.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Api(tags = "log", description = "日志接口")
@RestController
@RequestMapping("/log")
public class LogController {

    private final static Logger logger= LoggerFactory.getLogger(LogController.class);
    @Autowired
    private LogService logService;


    @ApiOperation("获取操作日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessManipulation", value = "操作类型" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "operatorName", value = "操作人员" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orgName", value = "公司名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "businessModule", value = "业务模块" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/operationlog/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<OperationLog>> listOperationLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final Integer businessManipulation, @RequestParam(required = false) final String operatorName,
                                                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
                                                                @RequestParam(required = false) String orgName,
                                                                @RequestParam(required = false) String businessModule,
                                                                @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<OperationLog>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DataBean<OperationLog>> msg = new MessageBean<>();
       /* Date date = ifAddOneDay(startTime, endTime);
        if (null != date) {
            endTime = date;
        }*/
        if (startTime != null && endTime != null) {
            long start = startTime.getTime();
            long end = endTime.getTime();
            if (end - start > 1000L * 60 * 60 * 24 * 365) {
                msg.setCode(BusinessCode.OPERATIONLOG_SPAN_YEAR.getCode());
                msg.setDescription(BusinessCode.OPERATIONLOG_SPAN_YEAR.getDescription());
                return msg;
            }
        }
        Integer start = (page <= 1) ? 0 : (page - 1) * pageSize;
        try {
            DataBean<OperationLog> dataBean = logService.fetchOperationLog(businessManipulation, operatorName,orgName,businessModule, startTime, endTime, start, pageSize);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("操作日志详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "日志Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTime", value = "操作时间", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/operationlog/detail.htm", method = RequestMethod.POST)
    public MessageBean<OperationLog> detailOperationLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id,
                                                        @RequestParam(required = true) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date operationTime) {
        if (null == user) {
            MessageBean<OperationLog> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<OperationLog> msg = new MessageBean<>();
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        try {
            OperationLog operationLog = logService.fetchOneOperationLog(id, operationTime);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setData(operationLog);
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("批量删除操作日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "operationLogs", value = "[{'id':'15913', 'operationTime':'2019-07-31 11:02:56'},..]", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/operationlog/batchDelete.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> batchDeleteOperationLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String operationLogs) {
        if (null == user) {
            MessageBean<Boolean> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Boolean> msg = new MessageBean<>();
        List<OperationLog> logList = null;
        try {
            logList = JSONObject.parseArray(operationLogs, OperationLog.class);
        } catch (Exception e) {
            msg.setCode(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getCode());
            msg.setDescription(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getDescription());
            return msg;
        }
        try {
            msg.setData(logService.batchDeteleOperationLog(logList));
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            msg.setCode(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getCode());
            msg.setDescription(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getDescription());
            return msg;
        }
        return msg;
    }


    private Date ifAddOneDay(Date startTime, Date endTime) {
        if (startTime != null && endTime != null && startTime.equals(endTime)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endTime);
            calendar.add(Calendar.DATE, 1);
            return calendar.getTime();
        }
        return null;
    }


    @ApiOperation("获取登录日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "signinName", value = "登录账号" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "browser", value = "浏览器" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orgName", value = "单位" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deptName", value = "部门名称" , dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/signinlog/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<SigninLog>> listSigninLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String signinName, @RequestParam(required = false) final String browser,
                                                          @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                                          @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
                                                          @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize,
                                                          @RequestParam(required = false) String orgName,@RequestParam(required = false) final String deptName) {
        if (null == user) {
            MessageBean<DataBean<SigninLog>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DataBean<SigninLog>> msg = new MessageBean<>();
        /*Date date = ifAddOneDay(startTime, endTime);
        if (null != date) {
            endTime = date;
        }*/
        Integer start = (page <= 1) ? 0 : (page - 1) * pageSize;
        try {
            DataBean<SigninLog> dataBean = logService.fetchSigninLog(signinName, browser, startTime, endTime, start, pageSize,orgName,deptName);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("登录日志详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "日志Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/signinlog/detail.htm", method = RequestMethod.POST)
    public MessageBean<SigninLog> detailSigninLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id) {
        if (null == user) {
            MessageBean<SigninLog> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<SigninLog> msg = new MessageBean<>();
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        try {
            SigninLog signinLog = logService.fetchOneSigninLog(id);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setData(signinLog);
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("批量删除登录日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "日志Id,多个之间用逗号分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/signinlog/batchDelete.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> batchDeleteSigninLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            MessageBean<Boolean> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Boolean> msg = new MessageBean<>();
        if (StringUtils.isEmpty(ids)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        try {
            String[] idArray = ids.split("[,，]");
            msg.setData(logService.batchDeteleSigninLog(Arrays.asList(idArray)));
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            msg.setCode(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getCode());
            msg.setDescription(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getDescription());
            return msg;
        }
        return msg;
    }


    @ApiOperation("获取在线日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "在线账号" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deptName", value = "部门名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "browser", value = "浏览器" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "在线状态" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/onlinelog/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<OnlineLog>> listOnlineLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String loginName, @RequestParam(required = false) final String deptName,
                                                          @RequestParam(required = false) final String browser, @RequestParam(required = false) final Integer status,
                                                          @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<OnlineLog>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DataBean<OnlineLog>> msg = new MessageBean<>();
        Integer start = (page <= 1) ? 0 : (page - 1) * pageSize;
        try {
            DataBean<OnlineLog> dataBean = logService.fetchOnlineLog(loginName, deptName, browser, status, start, pageSize);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("在线日志详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "日志Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/onlinelog/detail.htm", method = RequestMethod.POST)
    public MessageBean<OnlineLog> detailOnlineLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id) {
        if (null == user) {
            MessageBean<OnlineLog> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<OnlineLog> msg = new MessageBean<>();
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        try {
            OnlineLog signinLog = logService.fetchOneOnlineLog(id);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setData(signinLog);
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("批量删除在线日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "日志Id,多个之间用逗号分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/onlinelog/batchDelete.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> batchDeleteOnlineLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            MessageBean<Boolean> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Boolean> msg = new MessageBean<>();
        if (StringUtils.isEmpty(ids)) {
            msg.setCode(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.MESSAGE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        try {
            String[] idArray = ids.split("[,，]");
            msg.setData(logService.batchDeteleOnlineLog(Arrays.asList(idArray)));
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            msg.setCode(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getCode());
            msg.setDescription(BusinessCode.OPERATIONLOG_FORMAT_ERROR.getDescription());
            return msg;
        }
        return msg;
    }


}
